package com.jacen.fzxs.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jodd.util.StringUtil;

import com.alibaba.fastjson.JSON;

/**
 * servlet工具类
 * @author Administrator
 *
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class ServletUtils {
	public static final Integer ERROR_CODE = Integer.valueOf(0);
	public static final Integer NORMAL_CODE = Integer.valueOf(1);

	public static Integer getIntParam(HttpServletRequest request,
			String paramName) {
		String value = request.getParameter(paramName);
		return Integer.valueOf(Integer.parseInt(value));
	}

	/**
	 * 输出Json
	 * @param response
	 * @param code
	 * @param info
	 */
	public static void outputMsgInJson(HttpServletResponse response,
			Integer code, String info) {
		try {
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter writer = response.getWriter();
			Map map = new HashMap();
			map.put("code", code);
			map.put("msg", info);
			String str = JSON.toJSONString(map);
			writer.write(str);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 输出Html
	 * @param response
	 * @param sContent
	 */
	public static void outputHTML(HttpServletResponse response, String sContent) {
		try {
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.write(sContent);
			out.flush();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String getIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip)))
			ip = request.getHeader("Proxy-Client-IP");

		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip)))
			ip = request.getHeader("WL-Proxy-Client-IP");

		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip)))
			ip = request.getRemoteAddr();

		return ip;
	}

	public static Map<String, String> getParameterMap(HttpServletRequest request) throws Exception {
		Enumeration paramNames = request.getParameterNames();

		Map paramMap = new HashMap();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			paramMap.put(paramName, request.getParameter(paramName));
		}
		return paramMap;
	}

	public static <T> T getParamValue(Class<T> clazz,
			Map<String, String> paramsMap, String paramName) {
		String paramValue;
		try {
			paramValue = (String) paramsMap.get(paramName);
			if (StringUtil.isEmpty(paramValue))
				throw new Exception("参数值为空");

			if (clazz.equals(String.class))
				return (T) paramValue;
			if ((clazz.equals(Timestamp.class)) || (clazz.equals(Date.class)))
				return (T) DateUtils.str2Timestamp(paramValue,
						"yyyy-MM-dd HH:mm:ss");

			return (T) clazz.getMethod("valueOf", new Class[] { String.class })
					.invoke(null, new Object[] { paramValue });
		} catch (Exception e) {
		}
		return null;
	}

	public static <T> T getParamValue(HttpServletRequest request,
			String paramName, Class<T> clazz) {
		String paramValue;
		try {
			paramValue = request.getParameter(paramName);
			if (StringUtil.isEmpty(paramValue))
				throw new Exception();

			if (clazz.equals(String.class))
				return (T) paramValue;
			if ((clazz.equals(Timestamp.class)) || (clazz.equals(Date.class)))
				return (T) DateUtils.str2Timestamp(paramValue,
						"yyyy-MM-dd HH:mm:ss");

			return (T) clazz.getMethod("valueOf", new Class[] { String.class })
					.invoke(null, new Object[] { paramValue });
		} catch (Exception e) {
		}
		return null;
	}

	public static <T> T getEntity(HttpServletRequest request, Class<T> clazz) {
		return getEntity(request, clazz, "yyyy-MM-dd");
	}

	public static <T> T getEntity(HttpServletRequest request, Class<T> clazz,
			String dateFormat) {
		if (clazz == null)
			throw new RuntimeException("clazz不能为空");
		if (request == null)
			throw new RuntimeException("request不能为空");
		if (dateFormat == null)
			throw new RuntimeException("dateFormat不能为空");
		try {
			Object obj = clazz.newInstance();
			updateEntity(request, obj, dateFormat);
			return (T) obj;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static void updateEntity(HttpServletRequest request, Object entity) {
		updateEntity(request, entity, "yyyy-MM-dd");
	}

	public static void updateEntity(HttpServletRequest request, Object entity,
			String dateFormat) {
		if (entity == null)
			throw new RuntimeException("entity不能为空");
		if (request == null)
			throw new RuntimeException("request不能为空");
		if (dateFormat == null)
			throw new RuntimeException("dateFormat不能为空");
		try {
			Enumeration em = request.getParameterNames();
			while (em.hasMoreElements()) {
				String fieldName = (String) em.nextElement();
				if (!(BeanUtils.hasProperty(entity.getClass(), fieldName)))
					continue;

				String fieldValue = request.getParameter(fieldName).trim();
				if (StringUtil.isEmpty(fieldValue)) {
					BeanUtils.setProperty(entity, fieldName, null);
				} else {
					Class fieldType = BeanUtils.getPropertyType(
							entity.getClass(), fieldName);

					Object value = null;
					if (fieldType == String.class)
						value = fieldValue;
					else if ((fieldType == Timestamp.class)
							|| (fieldType == Date.class)|| (fieldType == java.util.Date.class))
						value = DateUtils.str2Timestamp(fieldValue, dateFormat);
					else
						value = fieldType.getMethod("valueOf",
								new Class[] { String.class }).invoke(null,
								new Object[] { fieldValue });

					BeanUtils.setProperty(entity, fieldName, value);
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
